﻿/*-------------------------------------------------------------------------
* 命名空间: XrayDirection.ViewModels/ChangeNextRecipeViewModel
* 类       名: ChangeNextRecipeViewModel
* 功      能:  TD
* 时      间:  2024/2/24 15:08:41
* 版      本:  V1.0
* 作      者:  Fioman
* 格      言:  Talk is cheap,show me the code ^_^
*-------------------------------------------------------------------------*/
using Prism.Commands;
using Prism.Events;
using Prism.Ioc;
using Prism.Mvvm;
using SiliconSelect.Common;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;
using XrayDirection.Common;
using XrayDirection.DAL.DataEntity;
using XrayDirection.DAL.LocalDataAccess;
using XrayDirection.HelperManager;
using XrayDirection.Services;
using XrayDirection.Views;

namespace XrayDirection.ViewModels
{
    public class ChangeNextRecipeViewModel : BindableBase
    {
        private IContainerProvider _containerProvider;
        private IWindowService _windowService;
        private readonly IEventAggregator _eventAggregator;

        /// <summary>
        /// 一页显示的数据个数
        /// </summary>
        private int _singlePageCount = 50;

        public ChangeNextRecipeViewModel(IContainerProvider containerProvider, IWindowService windowService, IEventAggregator eventAggregator)
        {
            _containerProvider = containerProvider;
            _windowService = windowService;
            _eventAggregator = eventAggregator;
            RefreshInputPlanOrders();
            DeleteRecipeCommand = new DelegateCommand(DoDeleteRecipeTask);
            ChangeRecipeCommand = new DelegateCommand(DoChangeRecipeTask);
            CancelChangeCommand = new DelegateCommand(DoCancelChangeTask);

            PageOperaterCommand = new DelegateCommand<string>(DoPageOperater);
        }

        private void DoPageOperater(string commandParameter)
        {
            if (!string.IsNullOrWhiteSpace(commandParameter))
            {
                switch (commandParameter)
                {
                    case "PrePage":
                        // 上一页
                        if (CurrentPage <= 1) return;
                        else
                        {
                            ResultSummaryPage!.Clear();
                            for (int i = (CurrentPage - 2) * _singlePageCount; i < _singlePageCount + (CurrentPage - 2) * _singlePageCount; i++)
                            {
                                ResultSummaryPage.Add(InputPlanOrders![i]);
                            }
                            CurrentPage--;
                            CurrentPageCount = ResultSummaryPage.Count;
                        }
                        break;
                    case "NextPage":
                        // 下一页
                        if (CurrentPage >= TotalPage) return;
                        else
                        {
                            ResultSummaryPage?.Clear();
                            int finalCountMax = Math.Min(CurrentPage * _singlePageCount + _singlePageCount, InputPlanOrders!.Count);
                            for (int i = CurrentPage * _singlePageCount; i < finalCountMax; i++)
                            {
                                ResultSummaryPage!.Add(InputPlanOrders[i]);
                            }
                            CurrentPage++;
                            CurrentPageCount = ResultSummaryPage!.Count;
                        }
                        break;
                    case "GoForward":
                        // 跳转指定页面
                        int number;
                        bool res = int.TryParse(CurrentPageShow, out number);
                        if (res)
                        {
                            // 如果成功了
                            if (number > TotalPage)
                            {
                                CurrentPage = TotalPage;
                            }
                            else if (number <= 1)
                            {
                                CurrentPage = 1;
                            }
                            else
                            {
                                CurrentPage = number;
                            }

                            ResultSummaryPage!.Clear();
                            int finalCountMax = Math.Min((CurrentPage - 1) * _singlePageCount + _singlePageCount, inputPlanOrders!.Count);

                            for (int i = (CurrentPage - 1) * _singlePageCount; i < finalCountMax; i++)
                            {
                                ResultSummaryPage.Add(inputPlanOrders![i]);
                            }
                            CurrentPageCount = ResultSummaryPage.Count;

                        }
                        else
                        {
                            MessageBox.Show("输入格式错误,请输入正确的数字!", "数据输入格式错误提示框", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                        break;
                    default:
                        break;
                }
            }
        }

        public DelegateCommand<string> PageOperaterCommand { get; private set; }
        public void PublishRecipeChangeEvent()
        {
            _eventAggregator.GetEvent<RecipeChangeEvent>().Publish(string.Empty);
        }

        private void DoCancelChangeTask()
        {
            // 直接关闭窗口即可
            _windowService.CloseWindow(nameof(ChangeNextRecipeView));
        }

        // 切换工单,切换工单的时候要注意一点,要先选中工单.
        private void DoChangeRecipeTask()
        {
            if (SelectedIndex != -1)
            {
                var orderUsed = InputPlanOrders[SelectedIndex];
                //OrderEntity order = new OrderEntity()
                //{
                //    RecipeName = orderUsed.RecipeName,
                //    CreateTime = DateTimeHelper.GetTimeNowForSql(),
                //    LongLengthX = orderUsed.LongLengthX,
                //    ShortLengthY = orderUsed.ShortLengthY,
                //    FrontEdgeDisD = orderUsed.FrontEdgeDisD,
                //    DirectHoleDisF = orderUsed.DirectHoleDisF,
                //    MoveOffset = orderUsed.MoveOffset,
                //    OkCount = 0,
                //    FailCount = 0,
                //    UpdateTime = DateTimeHelper.GetTimeNowForSql(),
                //};
                //var addRes = OrderAccess.AddOrderWithIdBack(order);
                if (true)
                {
                    // 切换后的工单Id,先更新到WorkingInfo中去.
                    var workingInfoRes = WorkingInfoAccess.GetWorkingInfos();
                    if (workingInfoRes.State)
                    {
                        var oldWorkingInfo = workingInfoRes.Data![0];
                        // 找到了当前作业的工单信息,然后更新它的内容
                        WorkingInfoEntity workingInfoNew = new WorkingInfoEntity()
                        {
                            Id = oldWorkingInfo.Id,
                            WorkingRecipeId = orderUsed.Id,
                            WorkingRecipeName = orderUsed.RecipeName,
                            BorderIndex = 1,
                            BorderIndexMax = oldWorkingInfo.BorderIndexMax,
                            CreateTime = DateTimeHelper.GetTimeNowForSql(),
                            UpdateTime = DateTimeHelper.GetTimeNowForSql(),
                        };
                        var updateRes = WorkingInfoAccess.UpdateWorkingInfo(workingInfoNew);
                        if (!updateRes.State)
                        {
                            MessageProvider.ShowError(updateRes.Message!, "数据库更新失败提示");
                        }
                        {
                            orderUsed.OkCount = 0;
                            orderUsed.FailCount = 0;
                            orderUsed.Count = 0;
                            OrderAccess.UpdateOrder(orderUsed);// 清除工单的计数数据
                            // 更新成功之后,去刷新一下工单,然后将当前的工单删除.
                            _containerProvider.Resolve<IndexViewModel>().RefreshWorkingInfo();
                            PublishRecipeChangeEvent();
                            // 工单对应目录创建,切换工单的时候需要做的事情.
                            _containerProvider.Resolve<IndexViewModel>().InitImageDir();
                            // 切换完工单之后,将搜索的字符串清空
                            SearchRecipeId = string.Empty;
                            // 关闭当前窗口
                            _windowService.CloseWindow(nameof(ChangeNextRecipeView));
                        }
                    }
                    else
                    {
                        LogHelper.WriteLog("数据库操作异常" + workingInfoRes.Message!);
                    }
                }
            }
            else
            {
                MessageProvider.ShowInfo("请选中你要切换的工单!", "工单切换提示");
            }
        }

        // 删除工单
        private void DoDeleteRecipeTask()
        {
            if (SelectedIndex != -1)
            {
                int deleteId = InputPlanOrders[SelectedIndex].Id;
                var result = OrderAccess.DeleteOrderById(deleteId);
                if (result.State)
                {
                    RefreshInputPlanOrders();
                }
                else
                {
                    MessageProvider.ShowError(result.Message!, "删除失败提示框");
                }
            }
        }

        public DelegateCommand DeleteRecipeCommand { get; private set; }
        public DelegateCommand ChangeRecipeCommand { get; private set; }
        public DelegateCommand CancelChangeCommand { get; private set; }

        private ObservableCollection<OrderEntity>? _resultSummaryPage = new ObservableCollection<OrderEntity>();

        public ObservableCollection<OrderEntity>? ResultSummaryPage
        {
            get { return _resultSummaryPage; }
            set
            {
                _resultSummaryPage = value;
                RaisePropertyChanged();
            }
        }

        private int _currentPage;

        public int CurrentPage
        {
            get { return _currentPage; }
            set
            {
                CurrentPageShow = $"{value} / {TotalPage}";
                _currentPage = value;
                RaisePropertyChanged();
            }
        }

        private int _totalPage;

        public int TotalPage
        {
            get { return _totalPage; }
            set
            {
                _totalPage = value;
                RaisePropertyChanged();
            }
        }


        private int _currentPageCount;

        public int CurrentPageCount
        {
            get { return _currentPageCount; }
            set
            {
                _currentPageCount = value;
                RaisePropertyChanged();
            }
        }

        private int _totalPageCount;

        public int TotalPageCount
        {
            get { return _totalPageCount; }
            set
            {
                _totalPageCount = value;
                RaisePropertyChanged();
            }
        }

        private string? _currentPageShow;

        public string? CurrentPageShow
        {
            get { return _currentPageShow; }
            set
            {
                _currentPageShow = value;
                RaisePropertyChanged();
            }
        }

        private string? _searchRecipeId = string.Empty;

        /// <summary>
        /// 要查询的SearchRecipeId
        /// </summary>
        public string? SearchRecipeId
        {
            get { return _searchRecipeId; }
            set
            {
                if (_searchRecipeId != value)
                {
                    _searchRecipeId = value;
                    RaisePropertyChanged();
                    // 当值发生变化的时候,就去刷新一次,但是刷新的时候
                    RefreshInputPlanOrders();
                }
            }
        }



        // 从数据库中刷新切换工单的那个表.
        public void RefreshInputPlanOrders()
        {
            DataResult<List<OrderEntity>> result;
            if (SearchRecipeId != null && SearchRecipeId.Trim() != string.Empty)
            {
                result = OrderAccess.GetOrdersByRecipeIdLikely(SearchRecipeId);
            }
            else
            {
                result = OrderAccess.GetOrders();
            }
            if (result.State)
            {
                InputPlanOrders.Clear();
                ResultSummaryPage?.Clear();
                foreach (var order in result.Data!)
                {
                    Application.Current?.Dispatcher?.Invoke(() =>
                    {
                        InputPlanOrders.Add(order);
                        if (InputPlanOrders.Count <= _singlePageCount)
                        {
                            ResultSummaryPage?.Add(order);
                        }
                    });
                }
                Application.Current?.Dispatcher?.Invoke(() =>
                {
                    // 每次数据更新的时候,分页信息也要更新一下
                    if (InputPlanOrders != null && ResultSummaryPage != null)
                    {
                        TotalPage = inputPlanOrders.Count / _singlePageCount + (inputPlanOrders.Count % _singlePageCount == 0 ? 0 : 1);
                        CurrentPageCount = ResultSummaryPage!.Count;
                        TotalPageCount = inputPlanOrders!.Count;
                        CurrentPage = 1;
                    }
                    //// 如果只有一页
                    //if (TotalPage <= 1)
                    //{
                    //    foreach (var item in ResultSummaryTotal)
                    //    {
                    //        ResultSummaryPage!.Add(item);
                    //    }
                    //}
                    //else
                    //{
                    //    for (int i = 0; i < _singlePageCount; i++)
                    //    {
                    //        ResultSummaryPage!.Add(ResultSummaryTotal[i]);
                    //    }
                    //}

                });
            }
            else
            {
                Application.Current?.Dispatcher?.Invoke(() =>
                {
                    ResultSummaryPage?.Clear();
                    TotalPage = 1;
                    CurrentPage = 1;
                    CurrentPageCount = 0;
                    TotalPageCount = 0;
                });
                MessageProvider.ShowError(result.Message!, "数据库操作失败");
            }

            if (ResultSummaryPage?.Count > 0)
            {
                SelectedIndex = 0;
            }
            else
            {
                SelectedIndex = -1;
            }
        }

        /// <summary>
        /// 选中某一行,如果不为空,就默认选中第一行.
        /// </summary>
        private int selectedIndex;

        public int SelectedIndex
        {
            get { return selectedIndex; }
            set
            {
                selectedIndex = value;
                RaisePropertyChanged();
            }
        }


        private ObservableCollection<OrderEntity> inputPlanOrders = new ObservableCollection<OrderEntity>();

        public ObservableCollection<OrderEntity> InputPlanOrders
        {
            get { return inputPlanOrders; }
            set
            {
                inputPlanOrders = value;
                RaisePropertyChanged();
            }
        }

    }
}
